﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace KINLO.DRV.Drv
{
    public class HWScannerDrv
    {
        Socket socket;
        string IP;
        int Port;
        string ID;
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(KNCScannerDrv));
        int RECV_DATA_MAX = 1024;
        public HWScannerDrv(string ip, int port, string id, int timeout)
        {
            try
            {
                IP = ip;
                Port = port;
                ID = id;
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                SendTimeout = timeout;
                ReceiveTimeout = timeout;
                socket.SendTimeout = SendTimeout;
                socket.ReceiveTimeout = ReceiveTimeout;
                log.Info(string.Format("创建 {0}号扫码枪 {1}:{2} 完成", ID, IP, Port));

            }
            catch (Exception ex)
            {
                log.Error(string.Format("创建 {0}号扫码枪 {1}:{2} 发生了异常:{3}", ID, IP, Port, ex));
                throw ex;
            }
        }


        public void StartScan()
        {
            try
            {

                if (!Connected)
                {
                    Open();
                }
                byte[] command = new byte[] { 22, 84, 13 };
                socket.Send(command);
                log.Info(string.Format("发送 {0}号扫码枪 {1}:{2} 发送扫描命令完成", ID, IP, Port));
            }
            catch (SocketException sex)
            {
            }
            catch (Exception ex)
            {
                log.Error(string.Format("启动 {0}号扫码枪 {1}:{2} 扫描时发生了异常:{3}", ID, IP, Port, ex));
                throw ex;
            }
        }
        public void Open()
        {
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.SendTimeout = SendTimeout;
                socket.ReceiveTimeout = ReceiveTimeout;
                socket.Connect(IP, Port);

                log.Info(string.Format("连接 {0}号扫码枪 {1}:{2} 成功", ID, IP, Port));
            }
            catch (Exception ex)
            {
                log.Error(string.Format("打开 {0}号扫码枪 {1}:{2} 发生了异常:{3}", ID, IP, Port, ex));
            }
        }
        public bool Connected
        {
            get
            {
                try
                {
                    Ping ping = new Ping();
                    var a = ping.Send(IP);
                    if (a.Status == IPStatus.Success && socket.Connected)
                    {
                        Console.WriteLine("Status:{0} Connected:{1}", a.Status, socket.Connected);
                        return true;
                    }
                    else
                    {
                        Console.WriteLine("Status:{0} Connected:{1}", a.Status, socket.Connected);
                        return false;
                    }
                }
                catch
                {
                    return false;
                }
            }
        }
        int receiveTimeout;
        public int ReceiveTimeout
        {
            get { return receiveTimeout; }
            set
            {
                receiveTimeout = value;
            }
        }
        int sendTimeout;
        public int SendTimeout
        {
            get { return sendTimeout; }
            set
            {
                sendTimeout = value;
            }
        }
        public string Receive()
        {
            try
            {
                Byte[] recvBytes = new Byte[RECV_DATA_MAX];
                if (socket.Connected)
                {
                    if (!(socket.Available>0))
                    {
                        Thread.Sleep(500);
                    }
                    if (!(socket.Available > 0))
                    {
                        Thread.Sleep(500);
                    }
                    if (!(socket.Available > 0))
                    {
                        throw new Exception(string.Format("扫码器:{0}:{1} 扫码超时",IP,Port));
                    }
                    var len = socket.Receive(recvBytes);
                    if (len > 0)
                    {
                        var barcode = Encoding.Default.GetString(recvBytes, 0, len);
                        log.Info(string.Format("读 {0}号扫码枪 {1}:{2} 完成", ID, IP, Port));
                        return barcode;
                    }
                }
                log.Info(string.Format("读 {0}号扫码枪 {1}:{2} 完成", ID, IP, Port));
                return "";
            }
            catch (Exception ex)
            {
                log.Error(string.Format("读 {0}号扫码枪 {1}:{2} 发生了异常:{3}", ID, IP, Port, ex));
                return "";
            }
            finally
            {
                StopScan();
            }
        }
        public void StopScan()
        {
            try
            {
                byte[] command = new byte[] { 22, 85, 13 };
                socket.Send(command);
                socket.Close();

                log.Info(string.Format("关闭 {0}号扫码枪 {1}:{2}", ID, IP, Port));
            }
            catch (Exception ex)
            {
                log.Error(string.Format("关闭时 {0}号扫码枪 {1}:{2} 发生了异常:{3}", ID, IP, Port, ex));
            }
        }
    }
}
